package designpatterns.prototype;

import java.util.Hashtable;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 2022/1/29 8:50
 */
public class ShapeCache {

    private static final Hashtable<String, Shape> SHAPE_HASHTABLE = new Hashtable<>();

    /**
     * 添加缓存数据
     */
    public static void loadCache() {
        Circle circle = new Circle();
        circle.setId("1");
        SHAPE_HASHTABLE.put(circle.getId(), circle);

        Square square = new Square();
        square.setId("2");
        SHAPE_HASHTABLE.put(square.getId(), square);

        Rectangle rectangle = new Rectangle();
        rectangle.setId("3");
        SHAPE_HASHTABLE.put(rectangle.getId(), rectangle);
    }

    /**
     * 使用原型模式创建需要的对象
     *
     * @param shapeId 图形的 Id
     * @return Shape
     */
    public static Shape getShape(String shapeId) {
        Shape cachedShape = SHAPE_HASHTABLE.get(shapeId);
        return (Shape) cachedShape.clone();
    }

}
